/* $RCSFile: DocumentDB.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Documents/DocumentDB.cs $
 * $log$
 * Revision 19 2010/08/09 09:43:52  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Configuration;
using AddonNice.UI.WebControls;
using AddonNice.Diagnostics;

namespace AddonNice.Settings.PageModules.Documents
{

	/// <summary>
	/// Class that encapsulates all data logic necessary to add/query/delete documents within the Portal database.
	/// </summary>
	public class DocumentDB : DBDataStore
    {

		/// <summary>
		/// The GetDocuments method returns a DataSet containing all of the
		/// documents for a specific portal module from the documents datatable.
		/// </summary>
		public SqlDataReader GetDocuments(int moduleID) 
        {
            SqlCommand myCommand			=	new SqlCommand("dbo.adn_GetDocuments", myConnection);
            myCommand.CommandType			=	CommandType.StoredProcedure;

            AddModuleIDParameters(myCommand,moduleID);

			SqlDataReader result			=	null;
			try
			{
				myConnection.Open();
				result						=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetDocuments moduleID: {0}, ex: {1}",moduleID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}


		/// <summary>
		/// Returns a SqlDataReader containing details about a 
		/// specific document from the Documents database table.
		/// </summary>
		public SqlDataReader GetSingleDocument(int itemID) 
		{
            SqlCommand myCommand				=	new SqlCommand("dbo.adn_GetSingleDocument", myConnection);
            myCommand.CommandType				=	CommandType.StoredProcedure;

            AddItemIDParameters(myCommand,itemID);

			SqlDataReader result				=	null;
			try
			{
				myConnection.Open();
				result							=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetSingleDocument itemID: {0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}

		/// <summary>
		/// Return the specified document content from datatable
		/// </summary>
		public SqlDataReader GetDocumentContent(int itemID) 
		{
            SqlCommand myCommand			=	new SqlCommand("dbo.adn_GetDocumentContent", myConnection);

            myCommand.CommandType			=	CommandType.StoredProcedure;

            AddItemIDParameters(myCommand,itemID);

			SqlDataReader result			=	null;
			try
			{
				myConnection.Open();
				result						=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetDocumentContent itemID: {0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}
                                                                                                             

		/// <summary>
		/// Deletes the specified document from the Documents database table
		/// and delete if exists the phisycal file from disk
		/// </summary>
		public void DeleteDocument(int itemID, string fileName)
        {
            //Physical delete
            try
            {
                File.Delete(@fileName);
            }
            catch(Exception exp)
            {
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB DeleteDocument  Physical delete itemID: {0}, fileName: {1}, ex: {2}",itemID,fileName, exp),DBTraceSwitch.Sw.Info);
			}

            // Delete from DB
            SqlCommand myCommand = new SqlCommand("dbo.adn_DeleteDocument", myConnection);

            myCommand.CommandType = CommandType.StoredProcedure;

            AddItemIDParameters(myCommand,itemID);

			try
			{
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB DeleteDocument  itemID: {0}, fileName: {1}, ex: {2}",itemID,fileName, exp),DBTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}

		}


		/// <summary>
		/// Insert or update the specified document within the Documents database table.
		/// </summary>
		public void UpdateDocument(int moduleID, int itemID, String userName, String name, String url, String category, byte[] content, int size, String contentType) 
        {

            if (userName.Length < 1) 
            {
                userName                    =   StStr.unknown;
            }

            SqlCommand myCommand			=	new SqlCommand("dbo.adn_UpdateDocument", myConnection);
            myCommand.CommandType			=	CommandType.StoredProcedure;

            AddItemIDParameters(myCommand,itemID);

            AddModuleIDParameters(myCommand,moduleID);

            SqlParameter parameterUserName	=	new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
            parameterUserName.Value			=	userName;
            myCommand.Parameters.Add(parameterUserName);

            SqlParameter parameterName		=	new SqlParameter("@FileFriendlyName", SqlDbType.NVarChar, 150);
            parameterName.Value				=	name;
            myCommand.Parameters.Add(parameterName);

            SqlParameter parameterFileUrl	=	new SqlParameter("@FileNameUrl", SqlDbType.NVarChar, 250);
            parameterFileUrl.Value			=	url;
            myCommand.Parameters.Add(parameterFileUrl);

            SqlParameter parameterCategory	=	new SqlParameter("@Category", SqlDbType.NVarChar, 50);
            parameterCategory.Value			=	category;
            myCommand.Parameters.Add(parameterCategory);

            SqlParameter parameterContent	=	new SqlParameter("@Content", SqlDbType.Image);
            parameterContent.Value			=	content;
            myCommand.Parameters.Add(parameterContent);

            SqlParameter parameterContentType = new SqlParameter("@ContentType", SqlDbType.NVarChar, 50);
            parameterContentType.Value		=	contentType;
            myCommand.Parameters.Add(parameterContentType);

            SqlParameter parameterContentSize =		new SqlParameter("@ContentSize", SqlDbType.Int, 4);
            parameterContentSize.Value		=	size;
            myCommand.Parameters.Add(parameterContentSize);

			try
			{
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB UpdateDocument  itemID:{0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}
		}   

		public DataView GetDsDocumentsGlobalized(int moduleID) 
		{
			SqlDataReader dr	=	null;
			try
			{
				dr              =   GetDocumentsGlobalized(moduleID);
				return PortalModuleControl.CreateDataView(dr);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetDsDocumentsGlobalized moduleID: {0}, ex: {1}",moduleID,exp),DBTraceSwitch.Sw.Info);
				if ( dr != null )
					dr.Close();
				throw;
			}
		}

        public DataTable GetDocumentsGlobalizedTb(int moduleID)
        {
            SqlDataAdapter myAdapt			    =   new SqlDataAdapter("dbo.adn_GetDocumentsGlobalized",myConnection);
            myAdapt.SelectCommand.CommandType   =   CommandType.StoredProcedure;

            AddGlobalizeParameters(myAdapt.SelectCommand);

            AddModuleIDParameters(myAdapt.SelectCommand,moduleID);

            DataTable myDataSet					=   new DataTable();
            try
            {
                myAdapt.Fill(myDataSet);
            }
            catch ( Exception exp )
            {
                if ( DBTraceSwitch.Sw.TraceError )
                    Trace.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]RatingDB GetDocumentsGlobalizedTb ex: {0}",exp),DBTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( myConnection.State == System.Data.ConnectionState.Open )
                    myConnection.Close();
            }
            return CheckDataTableForDates(myDataSet);
        }

		public SqlDataReader GetDocumentsGlobalized(int moduleID) 
		{
			SqlCommand myCommand				=	new SqlCommand("dbo.adn_GetDocumentsGlobalized", myConnection);
			myCommand.CommandType				=	CommandType.StoredProcedure;

			AddGlobalizeParameters(myCommand);

            AddModuleIDParameters(myCommand,moduleID);

			SqlDataReader result				=	null;
			try
			{
				myConnection.Open();
				result							=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetDocumentsGlobalized moduleID: {0}, ex: {1}",moduleID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}

		public SqlDataReader GetSingleDocumentGlobalized(int itemID) 
		{
			SqlCommand myCommand				=	new SqlCommand("dbo.adn_GetSingleDocumentGlobalized", myConnection);
			myCommand.CommandType				=	CommandType.StoredProcedure;

			AddGlobalizeParameters(myCommand);

            AddItemIDParameters(myCommand,itemID);

			SqlDataReader result				=	null;
			try
			{
				myConnection.Open();
				result							=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetSingleDocumentGlobalized itemID: {0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}

		public SqlDataReader GetDocumentContentGlobalized(int itemID) 
		{
			SqlCommand myCommand				=	new SqlCommand("dbo.adn_GetDocumentContentGlobalized", myConnection);
			myCommand.CommandType				=	CommandType.StoredProcedure;

			AddGlobalizeParameters(myCommand);

            AddItemIDParameters(myCommand,itemID);

			SqlDataReader result				=	null;
			try
			{
				myConnection.Open();
				result							=	myCommand.ExecuteReader(CommandBehavior.CloseConnection);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB GetDocumentContentGlobalized itemID: {0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				if ( result != null )
					result.Close();
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
				throw;
			}
			return result;
		}
                                                                                                             

		public void DeleteDocumentGlobalized(int itemID, string fileName)
		{
			//Physical delete
			try
			{
				File.Delete(@fileName);
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB DeleteDocumentGlobalized  itemID: {0}, fileName: {1}, ex: {2}",itemID,fileName, exp),DBTraceSwitch.Sw.Info);
			}

			// Delete from DB
			SqlCommand myCommand				= new SqlCommand("dbo.adn_DeleteDocumentGlobalized", myConnection);

			myCommand.CommandType				= CommandType.StoredProcedure;

            AddItemIDParameters(myCommand,itemID);

			try
			{
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB DeleteDocumentGlobalized  itemID: {0}, fileName: {1}, ex: {2}",itemID,fileName, exp),DBTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}

		}

		public void UpdateDocumentGlobalized(int moduleID, int itemID, String userName, String name, String url, String category, byte[] content, int size, String contentType) 
		{
			if (userName.Length < 1) 
			{
				userName                        =   StStr.unknown;
			}
			SqlCommand myCommand				=   new SqlCommand("dbo.adn_UpdateDocumentGlobalized", myConnection);
			myCommand.CommandType				=   CommandType.StoredProcedure;

			AddGlobalizeParameters(myCommand);

            AddItemIDParameters(myCommand,itemID);

            AddModuleIDParameters(myCommand,moduleID);

			SqlParameter parameterUserName		=   new SqlParameter("@UserName", SqlDbType.NVarChar, 100);
			parameterUserName.Value				=   userName;
			myCommand.Parameters.Add(parameterUserName);

			SqlParameter parameterName			=   new SqlParameter("@FileFriendlyName", SqlDbType.NVarChar, 150);
			parameterName.Value					=   name;
			myCommand.Parameters.Add(parameterName);

			SqlParameter parameterFileUrl		=   new SqlParameter("@FileNameUrl", SqlDbType.NVarChar, 250);
			parameterFileUrl.Value				=   url;
			myCommand.Parameters.Add(parameterFileUrl);

			SqlParameter parameterCategory		=   new SqlParameter("@Category", SqlDbType.NVarChar, 50);
			parameterCategory.Value				=   category;
			myCommand.Parameters.Add(parameterCategory);

			SqlParameter parameterContent		=   new SqlParameter("@Content", SqlDbType.Image);
			parameterContent.Value				=   content;
			myCommand.Parameters.Add(parameterContent);

			SqlParameter parameterContentType	=   new SqlParameter("@ContentType", SqlDbType.NVarChar, 50);
			parameterContentType.Value			=   contentType;
			myCommand.Parameters.Add(parameterContentType);

			SqlParameter parameterContentSize	=   new SqlParameter("@ContentSize", SqlDbType.Int, 4);
			parameterContentSize.Value			=   size;
			myCommand.Parameters.Add(parameterContentSize);

			try
			{
				myConnection.Open();
				myCommand.ExecuteNonQuery();
			}
			catch(Exception exp)
			{
				if (DBTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentDB UpdateDocumentGlobalized  itemID: {0}, ex: {1}",itemID,exp),DBTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( myConnection.State == System.Data.ConnectionState.Open )
					myConnection.Close();
			}
		}   
	
	}
}
